foreach:
The foreach loop is used to cycle through the elements of a collection. A collection is a group of objects. C# defines several types of collections, of which one is an array. It is excellent for iterating through collections. type var-name specifies the type and name of an iteration variable that will receive the values of the elements from the collection as the foreach iterates. One important point to remember is that the iteration variable is read-only as far as the array is concerned.
The foreach cycles through an array in sequence from the lowest index to the highest. Although the foreach loop iterates until all elements in an array have been examined, it is possible to terminate a foreach loop early by using a break statement.

 

Syntax:

               foreach(type var-name in collection) statements;

Program on foreach
class sample
{
static void Main(string[] args)
{
int[] a = new int[10];
int  i;

for (i = 0; i < 10; i++)
{
Console.WriteLine("Enter no");
a[i] = Convert.ToInt32(Console.ReadLine());
}
foreach (int k in a)
Console.WriteLine(k);
// we can use var keyword as a datatype
foreach (var k in a)
Console.WriteLine(k);
}

Program on foreach using double dimensional array
class sample
{
static void Main(string[] args)
{
int[,] a = new int[2, 2];

 

            int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine("Enter a matrics");
a[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
foreach (int k in a)
{
Console.WriteLine(k);
}
}
}